package com.suqiu.handler;

import com.rabbitmq.client.AMQP;
import com.rabbitmq.client.Channel;
import com.suqiu.constant.RabbitConstant;
import lombok.extern.slf4j.Slf4j;
import org.springframework.amqp.core.Message;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.stereotype.Component;

import java.io.IOException;
import java.nio.charset.StandardCharsets;

/**
 * 队列2 处理器
 *
 * @author suqiu
 */
@Slf4j
@Component
public class QueueTwoHandler {

    @RabbitListener(queues = RabbitConstant.QUEUE_TWO)
    public void directHandlerManualAck(Message message, Channel channel) {
        String s = new String(message.getBody());
        String replyTo = message.getMessageProperties().getReplyTo();
        String correlationId = message.getMessageProperties().getCorrelationId();
        //  如果手动ACK,消息会被监听消费,但是消息在队列中依旧存在,如果 未配置 acknowledge-mode 默认是会在消费完毕后自动ACK掉
        final long deliveryTag = message.getMessageProperties().getDeliveryTag();
        try {
            log.info("队列2，手动ACK，接收消息：{}", s + replyTo + correlationId);
            // 通知 MQ 消息已被成功消费,可以ACK了
            channel.basicAck(deliveryTag, false);
            log.info("转发到reply指定的队列....{}", replyTo);
            AMQP.BasicProperties basicProperties = new AMQP.BasicProperties().builder().correlationId(correlationId).build();
            channel.basicPublish(RabbitConstant.TOPIC_MODE_QUEUE, replyTo,basicProperties,"send to three....".getBytes(StandardCharsets.UTF_8));
        } catch (IOException e) {
            try {
                // 处理失败,重新压入MQ
                channel.basicRecover();
            } catch (IOException e1) {
                e1.printStackTrace();
            }
        }
    }
}
